<template>
  <div>
    <el-form
      class="input-form"
      label-position="right"
      label-width="120px"
      ref="editForm"
      :rules="propRules"
      :disabled="propReadonly"
      :model="form"
    >
      <div class="form-unit">待加工耗材信息</div>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="品名">
            <el-input v-model="form.matrName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="品规">
            <el-input v-model="form.matrSpec" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="效期">
            <el-input v-model="form.expDate" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="批次">
            <el-input v-model="form.lot" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="sn">
            <el-input v-model="form.sn" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="rfid">
            <el-input
              v-model="form.rfid"
              :disabled="form.sn == null || rfid != null"
              placeholder="在此设置光标，开始扫描RFID"
              @keyup.enter.native="txtScan(form.rfid)"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="仓库">
            <el-input v-model="form.warehouseName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="库位">
            <el-input v-model="form.locationName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-checkbox v-model="form.flagConsignment" disabled>寄售入库</el-checkbox>
            <el-checkbox v-model="form.flagOmoc" disabled>一物一码</el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="加工包装">
            <el-select
              v-model="form.packageUnit"
              filterable
              placeholder="请选择包装"
              @change="matrUnitChange"
            >
              <el-option
                v-for="item in matrUnits"
                :key="item.unit"
                :label="item.unit"
                :value="item.unit"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="加工数量">
            <el-input-number
              v-model="form.packageQty"
              :min="0"
              :max="maxQty"
              label="加工数量"
              :disabled="form.packageQty == 0 || form.sn != null"
            ></el-input-number>
            <el-button
              type="primary"
              style="margin-left:50px"
              @click="viewFormProcess()"
              :disabled="form.packageQty==0 || form.sn != null"
            >加工</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="批量绑定">
            <el-input-number
              v-model="bindingNumber"
              :min="0"
              :max="maxBindingQty"
              :disabled="!autoBinding"
            ></el-input-number>
            <el-switch v-model="autoBinding" active-color="#13ce66" style="margin-left:50px"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="form-unit">库存列表</div>
      <el-row>
        <div style="height:500px;">
          <data-view
            ref="childDataView"
            propViewKey="wm_stock_barcode"
            propViewForm="wm/stock-barcode/detail.vue"
            :propAutoFetchData="false"
            :propPreQueryWrapper="cpChildViewQueryWrapper"
            @extra-button-click="handleExtraButton"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-row>
    </el-form>
  </div>
</template>


<script>
import DataView from '@/components/DataView.vue'
import barcodeParse from '@/util/barcodeParse.js'
import MatrSelect from '@/components/base/MatrSelect'


export default {
  data() {
    return {
      form: {},
      maxQty: 0,
      packageUnits: [],
      matrId: '',
      sn: '',
      rfid: '',
      autoBinding: false,
      maxBindingQty: 0,
      bindingNumber: 0
    }
  },
  methods: {
    initData() {
      this.getAllBarcode(this.propInitData)
      this.maxQty = this.form.packageQty
      this.matrId = this.propInitData.matrId
      this.fetchPackageUnit(this.matrId)
    },
    getAllBarcode(postData) {
      this.$ajax.get('/wm/stock/get_barcode', { params: { lineId: this.propInitData.id } }).then(resp => {
        this.form = resp.data
      })
    },
    viewFormProcess() {
      this.$set(this.propInitData, 'lineId', this.propInitData.id)
      this.$set(this.propInitData, 'packageQty', this.form.packageQty)
      this.$set(this.propInitData, 'packageUnit', this.form.packageUnit)
      this.$ajax.post('/wm/stock/pack', this.propInitData).then(resp => {
        this.form = resp.data
        this.fetchData()
      })
    },
    handleExtraButton(para) {
      if (para.button.key == 'print') {
        const params = {
          labelKey: 'sn',
          data: para.rows
        }
        this.$ajax.post('/sys/printer/printLabel', params).then(res => {
          this.utilMessage.success('已推送打印标签')
        })
      }
    },
    fetchPackageUnit(matrId) {
      this.$ajax.get('/base/matrUnit/getByMatr', { params: { matrId: this.matrId } }).then(resp => {
        this.packageUnits = resp.data
      })
    },
    //更换包装单位后自动计算可加工数量form
    matrUnitChange(matrUnit) {
      let changeRate = this.packageUnits.filter(pu => pu.unit == matrUnit).map(pu => pu.rate)[0]
      this.form.packageQty = Math.floor(this.form.skuQty / changeRate)
      this.maxQty = this.form.packageQty
      this.fetchPackageUnit(this.matrId)
    },
    handleCurrentChange(row) {
      this.form = row.row.row
      this.sn = row.row.row.sn
      this.rfid = row.row.row.rfid
      this.maxBindingQty = this.$refs.childDataView.getRows().length - row.row.rowIndex
      this.bindingNumber = this.maxBindingQty
    },
    txtScan(code) {
      if (this.autoBinding != true) {
        this.bindingNumber = 1
      }
      let codeType = barcodeParse.barCodeType(code)
      if (codeType == 'RFID') {
        for (let index = 0; index < this.bindingNumber; index += 1) {
          if (this.rfid == null) {
            const params = { sn: this.sn, rfid: code }
            this.$ajax.post('/wm/stock/binding_rfid', params).then(resp => {
              this.$nextTick(() => {
                this.fetchData()
              })
            })
            this.sn = this.sn.replace(/[^a-z]+/gi, '') + this.bindingBarcode(this.sn.replace(/[^0-9]/gi, ''))
            code = code.replace(/[^a-z]+/gi, '') + this.bindingBarcode(code.replace(/[^0-9]/gi, ''))
          } else {
            this.$confirm('该耗材已绑定RFID,是否解绑?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(() => {
                this.utilMessage.success('解绑成功!')
                this.form.rfid = null
              })
              .catch(() => {
                this.utilMessage.info('已取消')
              })
          }
        }
      } else {
        this.utilMessage.error('RFID格式错误')
      }
      this.rfid = this.form.rfid
    },
    fetchData() {
      this.$refs.childDataView.fetchData()
    },
    bindingBarcode(a) {
      let res = ''
      let temp = 0
      a = a.split('')
      let b = '0' + 1
      b = b.split('')
      while (a.length || b.length || temp) {
        temp += ~~a.pop() + ~~b.pop()
        res = (temp % 10) + res
        temp = temp > 9
      }
      return res
    }
  },
  created() {
    this.initData()
    this.$emit('event-register', {
      validate: callback => {
        this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        this.maxQty = formData.packageQty
        this.fetchPackageUnit(this.matrId)
      },
      afterSave: () => {},
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {},
      beforeFlow: flowButtonKey => {
        return true
      },
      afterFlow: flowButtonKey => {},
      beforeClose: () => {
        return true
      }
    })
  },
  mounted() {
    this.fetchData()
  },
  props: {
    propInitData: Object,
    propCurrentRow: Object,
    propReadonly: Boolean,
    propRules: Object,
    propFlowKey: String
  },
  components: {
    DataView,
    MatrSelect
  },
  computed: {
    cpChildViewQueryWrapper() {
      let wrapper = this.$newWrapper()
      wrapper.eq('lineId', this.propInitData.id)
      return wrapper
    },
    //针对未编码的库存 一物一码的可以且只能选择最小单位 非一物一码的能选择最小单位之外的其他单位
    //针对已编码的库存（非一物一码）只能选择非原先单位和最小单位的其他单位
    matrUnits() {
      if (!this.form.flagUniqueCode) {
        if (this.form.flagOmoc) {
          return this.packageUnits.filter(unit => unit.flagBase == 1)
        } else {
          return this.packageUnits.filter(unit => unit.flagBase != 1)
        }
      } else if (!this.form.flagOmoc) {
        return this.packageUnits.filter(unit => unit.flagBase != 1 && unit.unit != this.form.packageUnit)
      }
      return this.packageUnits
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
}
</style>
